package com.lagou.edu.service.impl;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.lagou.edu.service.GuavaCacheService;

import java.util.Iterator;
import java.util.concurrent.TimeUnit;

public class GuavaCacheServiceImpl implements GuavaCacheService{

	private Cache<String, Object> cache;

	public static GuavaCacheService getInstance() {
		return new GuavaCacheServiceImpl();
	}


	private GuavaCacheServiceImpl() {
		cache = CacheBuilder.newBuilder()
				.expireAfterWrite(15, TimeUnit.SECONDS)
				.recordStats()
				.build();
	}


	@Override
	public void displayCache() {
		if (cache == null) {
			return;
		}
		Iterator its = cache.asMap().entrySet().iterator();
		while (its.hasNext()) {
			System.out.println(its.next().toString());
		}
	}

	@Override
	public Object get(String key) {
		return cache.getIfPresent(key);
	}

	@Override
	public void put(String key, Object value) {
		cache.put(key, value);
	}





}
